package com.xxwy.lifecycle.definition;

import com.xxwy.lifecycle.bean.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;

/**
 * 1.获取元信息阶段.
 *  a.资源
 *      xml：XmlBeanDefinitionReader
 *      properties: PropertiesBeanDefinitionReader
 *      groovy: GroovyBeanDefinitionReader
 *  b.注解
 *      AnnotatedBeanDefinitionReader
 * 2. BeanDefinition注册
 * 3. BeanDefinition合并
 * @author xxwy
 * @date 2021/7/13 0013
 */
public class BeanMetaDataConfigurationDemo {

    /**
     * PropertiesBeanDefinitionReader
     */
    private static void resourceReader(DefaultListableBeanFactory beanFactory) {
        // add propertiesBeanDefinition
        PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);
        EncodedResource encodedResource = new EncodedResource(new ClassPathResource("META-INF/user.properties"), "UTF-8");
        beanDefinitionReader.loadBeanDefinitions(encodedResource);

        //get Bean
        System.out.println("加载的Bean有：" + beanFactory.getBeanDefinitionCount());
        System.out.println(beanFactory.getBean("user", User.class));
    }

    /**
     * AnnotatedBeanDefinitionReader
     * @param beanFactory
     */
    private static void annotatedReader(DefaultListableBeanFactory beanFactory) {
        AnnotatedBeanDefinitionReader beanDefinitionReader = new AnnotatedBeanDefinitionReader(beanFactory);
        // 注册当前类
        beanDefinitionReader.register(BeanMetaDataConfigurationDemo.class);

        System.out.println("加载的Bean有：" + beanFactory.getBeanDefinitionCount());
        System.out.println(beanFactory.getBean("beanMetaDataConfigurationDemo", BeanMetaDataConfigurationDemo.class));
    }

    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        annotatedReader(beanFactory);

    }

}
